
import React from 'react';
import { browserHistory } from 'react-router'

import dashed from '../img/order/dashed.png'
import dashed_white from '../img/order/dashed_white.png'
import checked from '../img/order/checked.png'
import unchecked from '../img/order/unchecked.png'
import stamp from '../img/order/stamp.png'
import hint from '../img/order/hint.png'
import arrow from '../img/order/arrow.png'
import button from '../img/material/button.png'
import {DynPath,customerInfo,ROOTURL,ROOTAPI,getParamValue,objToForm} from '../../publicAPI/publicAPI.js'
require('../css/FacialmaskOrder.css');
class FacialmaskOrder extends React.Component {
	constructor(props) {
	    super(props);
	    this.state = {
            filmcloth:this.props.filmcloth,//膜布
            hyaluronicacid:this.props.hyaluronicacid,//玻尿酸
            essentialoilsa:this.props.essentialoilsa,//玫瑰精油
            essentialoilsb:this.props.essentialoilsb,//薰衣草精油
            essence:this.props.essence,//香精味道
            effect:this.props.effect,//功效
            moiskin:this.props.moiskin,//霍霍芭油
            preservative:this.props.preservative,//防腐剂
            num:this.props.num,//数量
            zhiwujinghua1:this.props.zhiwujinghua1,
            zhiwujinghau2:this.props.zhiwujinghau2,
            zhiwujinghua3:this.props.zhiwujinghua3,
            item:{},
            allprice: 0,
            discount_list: [],
            discount_word: '',
            discount_id: '',
            discount_type: 0,
            originalprice: 0
	    }
	}
	componentWillMount() {
    }
    componentDidMount() {
        sessionStorage.setItem("scrollAct","true")
        let _this = this;
        let getCoupon=function(){
            let { id } = JSON.parse(localStorage.getItem('customerInfo'));
            var url = ROOTAPI+'kabuy/coupon/coupon/search.api'
            fetch(url, {
                method : 'POST',
                mode: 'cors',
                body: JSON.stringify({
                    where: {
                     possessorId: [
                        ['eq', id]
                     ],
                     stConsume: [
                        ['eq',false]
                     ]
                    }
                })
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        let items = [];
                        for(let i = 0;i < data.length; i ++) {
                            if(data[i].tmDeteriorate+86400000 < new Date().getTime()) {

                            }else {
                                items.push(data[i]);
                            }
                        }
                        _this.setState({                       
                            discount_list:items  
                        })                   
                    })
                }
            }) 
        }
        customerInfo(getCoupon);
    }
    componentWillReceiveProps(nextProps) {
        console.log(nextProps)
        this.total_price(nextProps)
    }
    total_price(nextProps) {
        let allprice = 0;
        let item = nextProps.item;
        let ItemOption={
                "mobu":nextProps.filmcloth.name,                        
                "bolisuan":nextProps.hyaluronicacid.name,                        
                "meiguijingyou":nextProps.essentialoilsa.name,                        
                "xunyicaojingyou":nextProps.essentialoilsb.name,                        
                "xiangjing":nextProps.essence.name,                        
                "meibai":nextProps.effect.name,                        
                "fangfuji":nextProps.preservative.name,                        
                "zirun":nextProps.moiskin.name,                        
                // "shuliang":nextProps.num.name,
                "zhiwu1":nextProps.zhiwujinghua1.name,
                "zhiwu2":nextProps.zhiwujinghua2.name,
                "zhiwu3":nextProps.zhiwujinghua3.name
            }
            // console.log(ItemOption)
        for(var n in ItemOption){
            for(var key in item[n].options){
                if(ItemOption[n]==key){
                    allprice+=parseFloat(item[n].options[key].price)
                }
            } 
            
        }
        allprice = allprice + 6;//加上基础价
        if(nextProps.num.name == 'shuliang-a') {
            allprice = allprice * 6;
        }
        if(nextProps.num.name == 'shuliang-b') {
            allprice = allprice * 12 * 0.9;
        }
        
        this.setState({
            originalprice: allprice,
            allprice: this.discountPrice(allprice,this.state.discount_type),
        })
        
    }
    clickBack() {
        browserHistory.push('/')
    }
    showCover() {
        // 必填项检测
        // 膜布
        let filmcloth = this.props.filmcloth.dname; 
        // 玻尿酸
        let hyaluronicacid = this.props.hyaluronicacid.dname;
        // 香味
        let essence = this.props.essence.dname || this.props.essentialoilsa.dname || this.props.essentialoilsb.dname;
        // 功效
        let effect = this.props.effect.dname || this.props.moiskin.dname || this.props.preservative.dname
        // 植物精华
        let zhiwujinghua = this.props.zhiwujinghua1.dname || this.props.zhiwujinghua2.dname || this.props.zhiwujinghua3.dname
        // 数量
        let num = this.props.num.dname
        if (filmcloth=='' || hyaluronicacid=='' || essence=='' || effect=='' || zhiwujinghua=='' || num=='') {
            let alert_message = "亲，请选择";
            
            if (filmcloth == '') alert_message += "膜布 ";
            if (hyaluronicacid == '') alert_message += "玻尿酸 ";
            if (essence == '') alert_message += "香味 ";
            if (effect == '') alert_message += "功效添加 ";
            if (zhiwujinghua == '') alert_message += "植物精华 ";
            if (num == '') alert_message += "数量 ";

            alert_message += "哦！"
            alert(alert_message)
        } else {
            // 打开弹框
            document.getElementsByClassName('fm-order-cover')[0].style.display = 'block';
        }
        
    }
    clickConfirm() {
        // 关闭遮罩层
        document.getElementsByClassName('fm-order-cover')[0].style.display = 'none';

        let {id} = JSON.parse(localStorage.getItem("customerInfo"));
        // let id = 4;
        let url = ROOTAPI+'kabuy/contract/instance.api'
        fetch(url, {
                method : 'POST',
                credentials: 'include',
                body:JSON.stringify({
                    customerId:id,
                    item:{
                        id:1
                    },
                    itemCounts:1,
                    meta:{
                        "ItemOption":{
                            "mobu": this.props.filmcloth.name,                        
                            "bolisuan": this.props.hyaluronicacid.name,                        
                            "meiguijingyou": this.props.essentialoilsa.name,                        
                            "xunyicaojingyou": this.props.essentialoilsb.name,                        
                            "xiangjing": this.props.essence.name,                        
                            "meibai": this.props.effect.name,                        
                            "fangfuji": this.props.preservative.name,                        
                            "zirun": this.props.moiskin.name,                        
                            "shuliang": this.props.num.name,
                            "zhiwu1": this.props.zhiwujinghua1.name,
                            "zhiwu2": this.props.zhiwujinghua2.name,
                            "zhiwu3": this.props.zhiwujinghua3.name,
                        }
                    }
                })
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        this.useDiscount(data.id);
                    })
                }else{
                    alert("错误")
                }
        })
    }
    /*使用优惠券*/
    useDiscount(id) {
        let url = ROOTAPI+'kabuy/contract/apply-coupon.api'
        fetch(url, {
                method : 'POST',
                credentials: 'include',
                headers: {"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"},
                body:objToForm({id: id,coupons: this.state.discount_id})
            }).then(res=>{
                if(res.ok){
                    res.json().then(data=>{
                        browserHistory.push({pathname:'/address',query:{
                                  id:data.id,
                                  netPay:data.netPay
                                }
                            })
                    })
                }else{
                    res.json().then(data=>{
                        alert(data.msg)
                    })
                }
            })
                        
    }
    reSelection(param) {
        this.props.callback(param)
    }
    showDiscount() {
        sessionStorage.setItem("scrollAct","false")
        document.getElementsByClassName('fm-order-discountCover')[0].style.display = 'block';
    }
    closeDiscount() {
        sessionStorage.setItem("scrollAct","true")
        document.getElementsByClassName('fm-order-discountCover')[0].style.display = 'none';
    }
    /*选择优惠券*/
    chooseDiscount(item) {
        this.setState({
            discount_word: item.couponType.dname,
            discount_id: item.id,
            discount_type: item.couponTypeId
        })
        let price = this.state.originalprice;
        this.setState({
            allprice: this.discountPrice(price,item.couponTypeId)
        })
        // 关闭遮罩层
        sessionStorage.setItem("scrollAct","true");
        document.getElementsByClassName('fm-order-discountCover')[0].style.display = 'none';
    }
    cancelDiscount() {
        this.setState({
            discount_word: '不使用优惠券',
            discount_id: '',
            discount_type: 0
        });
        let price = this.state.originalprice;
        this.setState({
            allprice: this.discountPrice(price,0)
        });
        // 关闭遮罩层
        sessionStorage.setItem("scrollAct","true");
        document.getElementsByClassName('fm-order-discountCover')[0].style.display = 'none';
    }
    /*计算打折后价格*/
    discountPrice(price,type) {
        switch(type){
            case 1:
                price = price * 0;
                price = price.toFixed(2);
                break;
            case 2:
                price = price * 0.6;
                price = price.toFixed(2);
                break;
            case 3:
                price = price * 0.7;
                price = price.toFixed(2);
                break;
            case 4:
                price = price * 0.8;
                price = price.toFixed(2);
                break;
            case 5:
                price = price * 0.9;
                price = price.toFixed(2);
                break;
            case 6:
                price = price * 0.95;
                price = price.toFixed(2);
                break;
            default:
                price = price.toFixed(2);
        }
        return price;
    }
    render() {
        console.log(this.state.allprice);
        return (
            <div className="fm-order" style={{top: "600%"}} id="fmpage7">
                <div className="fm-order-cover">
                    <div className="fm-order-cover-remind">
                        <div className="fm-order-cover-remind-img"><img src={hint}/></div>
                        <div className="fm-order-cover-remind-content">
                            <div className="fm-order-cover-remind-content-title1">
                                温馨提示
                            </div>
                            <div className="fm-order-cover-remind-content-word1">
                                面膜是由主要部分和基础部分组成，其中主要部分供用户定制选取，而基础部分会默认全部提供于每一片面膜中。
                            </div>
                            <div className="fm-order-cover-remind-content-title2">
                                基础部分成份如下：
                            </div>
                            <div className="fm-order-cover-remind-content-word2">
                                夏威夷坚果油<br/>
                                紫草提取液<br/>
                                金缕梅提取液<br/>
                                马齿苋（PORTULACA OLERACEA）提取物<br/>
                                丙二醇<br/>
                                维生素E<br/>
                                大米发酵乳化剂
                            </div>
                        </div>
                    </div>
                    <div className="fm-order-cover-button" onClick={this.clickConfirm.bind(this)}>
                        知道啦！下一步！
                    </div>
                </div>
                <div className="fm-order-discountCover">
                    <div className="fm-order-discountCover-button" onClick={this.closeDiscount.bind(this)}>
                        <img src={button}/>
                    </div>
                    <div className="fm-order-discountCover-content">
                        <div className="fm-order-discountCover-content-title">
                            <div onClick={this.cancelDiscount.bind(this)}>不使用优惠券</div>
                        </div>
                        <div className="fm-order-discountCover-content-list">
                            {
                                this.state.discount_list.map(function(item, index){
                                    return (
                                        <div className="fm-order-discountCover-content-list-item" key={index} onClick={this.chooseDiscount.bind(this,item)}>
                                            {item.couponType.dname}
                                            {this.state.discount_list.length!=(index+1)?<div className="fm-order-discountCover-content-list-item-img"><img src={dashed_white}/></div>:""}            
                                        </div>
                                    )  
                                },this)                      
                            }
                            
                        </div>
                    </div>
                </div>
                <div className="fm-order-table">
                    <div className="fm-order-table-title">
                        <div className="fm-order-table-title-word1">
                            萌拼面膜成份定制表
                        </div>
                        <div className="fm-order-table-title-stamp">
                            <img src={stamp}/>
                        </div>
                    </div>
                    <div className="fm-order-table-content">
                        <div className="fm-order-table-mobu">
                            <div className="fm-order-table-mobu-word1">膜布</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,0)}>重选</div>
                            <div className="fm-order-table-mobu-word2">{this.props.filmcloth.dname}</div>
                            <div className="fm-order-table-mobu-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-boniaosuan">
                            <div className="fm-order-table-boniaosuan-word1">玻尿酸</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-1)}>重选</div>
                            <div className="fm-order-table-boniaosuan-word2">{this.props.hyaluronicacid.dname}</div>
                            <div className="fm-order-table-boniaosuan-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-xiangwei">
                            <div className="fm-order-table-xiangwei-word1">香味</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-2)}>重选</div>
                            <div className="fm-order-table-xiangwei-words">
                                {this.props.essence.dname!=""?<div>{this.props.essence.dname}</div>:""}
                                {this.props.essentialoilsa.dname!=""?<div>{this.props.essentialoilsa.dname}</div>:""}
                                {this.props.essentialoilsb.dname!=""?<div>{this.props.essentialoilsb.dname}</div>:""}
                            </div>
                            <div className="fm-order-table-xiangwei-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-gongxiao">
                            <div className="fm-order-table-gongxiao-word1">功效添加</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-3)}>重选</div>
                            <div className="fm-order-table-gongxiao-words">
                                {this.props.effect.dname!=""?<div>{this.props.effect.dname}</div>:""}
                                {this.props.moiskin.dname!=""?<div>{this.props.moiskin.dname}</div>:""}
                                {(this.props.effect.dname=="" && this.props.moiskin.dname=="")?<div>无</div>:""}
                            </div>
                            <div className="fm-order-table-gongxiao-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-fangfu">
                            <div className="fm-order-table-fangfu-word1">防腐剂</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-3)}>重选</div>
                            <div className="fm-order-table-fangfu-img">
                                {this.props.preservative.dname!=""?<img src={checked} />:<img src={unchecked} />}
                            </div>
                            <div className="fm-order-table-fangfu-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-zhiwu">
                            <div className="fm-order-table-zhiwu-word1">植物精华</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-4)}>重选</div>
                            <div className="fm-order-table-zhiwu-words">
                                <div>{this.props.zhiwujinghua1.dname}</div>
                                <div>{this.props.zhiwujinghua2.dname}</div>
                                <div>{this.props.zhiwujinghua3.dname}</div>
                            </div>
                            <div className="fm-order-table-zhiwu-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-num">
                            <div className="fm-order-table-num-word1">数量</div>
                            <div className="fm-order-table-reelect" onClick={this.reSelection.bind(this,-5)}>重选</div>
                            <div className="fm-order-table-num-word2">{this.props.num.dname}</div>
                            <div className="fm-order-table-num-dashed"><img src={dashed}/></div>
                            <div className="clear"></div>
                        </div>
                        <div className="fm-order-table-discount" onClick={this.showDiscount.bind(this)}>
                            <div className="fm-order-table-discount-word1">优惠券</div>
                            <div className="fm-order-table-discount-arrow"><img src={arrow}/></div>
                            {this.state.discount_word == ''?
                                <div className="fm-order-table-discount-word2">{this.state.discount_list.length > 0 ? this.state.discount_list.length+'张' : '无'}</div>
                                :<div className="fm-order-table-discount-word2">{this.state.discount_word}</div>
                            }
                            <div className="clear"></div>
                        </div>
                    </div>
                </div>
                <div className="fm-order-button">
                    <div className="fm-order-button-price">
                        <span>价格：</span>
                        <span className="fm-order-button-price-money">&yen;{this.state.allprice}</span>
                    </div>
                    <div className="fm-order-button-confirm" onClick={this.showCover.bind(this)}>
                        确定啦！买单！
                    </div>
                    <div className="clear"></div>
                </div>
            </div>
        )
    }
}


export default FacialmaskOrder;